#include "recbox.h"
#include "ui_recbox.h"
#include "recboxitem.h"
#include<QJsonObject>

RecBox::RecBox(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::RecBox),
    row(1),
    col(4),
    currentIndex(0)
{
    ui->setupUi(this);
//    RecBoxItem* item = new RecBoxItem();  测试
//    ui->recListUpHLayout->addWidget(item);
}

RecBox::~RecBox()
{
    delete ui;
}

void RecBox::initRecBoxUi(QJsonArray data,int row)
{
    if(row==2)
    {
        this->row=row;
        this->col=8;
    }
    else
    {
        ui->recListDown->hide();
    }
    imageList=data;
    addRecBoxItem();
}

void RecBox::addRecBoxItem()
{
    //清楚前一组图片，添加新的一组
    QList<RecBoxItem*> recUpList=this->findChildren<RecBoxItem*>();
    for(auto&e:recUpList)
    {
        ui->recListUpHLayout->removeWidget(e);
        delete e;//释放之前创建的item对象
    }

    QList<RecBoxItem*> recDownList=this->findChildren<RecBoxItem*>();
    for(auto&e:recDownList)
    {
        ui->recListDownHLayout->removeWidget(e);
        delete e;//释放之前创建的item对象
    }

    int index=0;

    for(int i=currentIndex*col;i<col+currentIndex*col;i++)
    {
        QJsonObject obj=imageList[i].toObject();
        RecBoxItem* item=new RecBoxItem();//this???
        item->setImage(obj.value("path").toString());
        item->setText(obj.value("text").toString());
        if(index>=col/2&&row==2)//这里不能使用i因为i可能一直大于col/2,导致下面没有图片
        {
            ui->recListDownHLayout->addWidget(item);
        }
        else
        ui->recListUpHLayout->addWidget(item);
        index++;
    }
}


void RecBox::on_myUp_clicked()
{
    count=imageList.size()/col;//9
    currentIndex--;//0
    if(currentIndex<0)
    {
        currentIndex=count-1;
    }
    addRecBoxItem();
}

void RecBox::on_myDown_clicked()
{
    count=imageList.size()/col;
    currentIndex++;
    if(currentIndex>=count)
    {
        currentIndex=0;
    }
    addRecBoxItem();
}
